//
//  BDVIPViewController.m
//  BadBoy
//
//  Created by wen on 2016/12/26.
//  Copyright © 2016年 niusaibing. All rights reserved.
//

#import "BDVIPViewController.h"
#import "BDVIPTableViewCell.h"
#import "BDUserModel.h"
#import "BDVipPayView.h"
#import "BDRuzhuCityChooseView.h"
#import "AppDelegate.h"
#import <StoreKit/StoreKit.h>
#import "BDPayViewController.h"

@interface BDVIPViewController ()<UITableViewDelegate,UITableViewDataSource,SKProductsRequestDelegate,SKPaymentTransactionObserver>
{
    NSString *_order_info;
}

@property (nonatomic, strong) UIImageView *vipImageview;
@property (nonatomic, strong) UIImageView *avatarimageView;
@property (nonatomic, strong) UILabel *nameLabel;

@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) UIButton *backButton;

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) NSArray *datasource;

@property (nonatomic, strong) NSString *currentProId;
@property (nonatomic, strong) UIImageView *levelImageView;

@end

@implementation BDVIPViewController

+ (instancetype)sharedViewController{
    static BDVIPViewController *vipViewController;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        vipViewController = [[BDVIPViewController alloc] init];
    });
    return vipViewController;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:self.backButton];
    
    [self requestDatasource];
    [[self.backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self updateInfo];
}

- (void)loginSuccessRefresh{
    [self requestDatasource];
}

- (void)requestDatasource{
    
    BOOL isControl = [[[NSUserDefaults standardUserDefaults] objectForKey:@"versionControl"] boolValue];
    BDUserModel *currentUser = [BDUserModel getCurrentUser];
    
    NSString *type = @"1";
    if (isControl == YES || currentUser.is_auth == NO){
        type = @"2";
    }
    NSString *url = [NSString stringWithFormat:@"%@products?page=%@&size=%@&category=2&type=%@", KBDBaseURL, self.startPage, self.pageSize, type];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        self.datasource = x[@"list"];
        [self updateInfo];
        
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        // BDLog(ASLocalizedString(@"请求数据失败%@"), error);
    }];
}

- (void)updateInfo{
    
    BDUserModel *user = [BDUserModel getCurrentUser];
    [self.avatarimageView sd_setImageWithURL:[NSURL URLWithString:user.cover] placeholderImage:[UIImage imageNamed:@"avatar"]];
    self.nameLabel.text = user.nickname;
    [self.nameLabel sizeToFit];
    self.nameLabel.left = self.avatarimageView.right + 8;
    self.nameLabel.centerY = self.avatarimageView.centerY;
    
    _levelImageView.size = CGSizeMake(22 / 2, 26 / 2);
    _levelImageView.left = self.nameLabel.right + 5;
    _levelImageView.centerY = self.nameLabel.centerY;
    _levelImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"leve%ld",[user.points[@"level"] integerValue]]];

    self.vipImageview.image = [UIImage imageNamed:[NSString stringWithFormat:@"vip_%@_pic", @(user.vip_level)]];
    if (user.vip_level == 0) {
        self.timeLabel.text = ASLocalizedString(@"开通会员尊享特权");
    }else {
        NSDate *curDate = [NSDate dateWithTimeIntervalSince1970:user.vip_validity];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy.MM.dd"];
        NSString *dateStr = [formatter stringFromDate:curDate];
        self.timeLabel.text = [NSString stringWithFormat:ASLocalizedString(@"有效期：%@"), dateStr];
    }
    [self.timeLabel sizeToFit];
    self.timeLabel.bottom = self.vipImageview.height - 20;
    self.timeLabel.right = self.vipImageview.width - 20;
    
    [self.tableview reloadData];
    [self.view bringSubviewToFront:self.backButton];
}

#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cellID";
    BDVIPTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[BDVIPTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    __strong NSDictionary *model = self.datasource[indexPath.row];
    
    [cell configeWithModel:model buttonAction:^{
        BDUserModel *curUser = [BDUserModel getCurrentUser];
        if (curUser.is_guest == YES){
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"温馨提示")message:ASLocalizedString(@"游客身份购买VIP将不支持另一设备使用vip功能。是否前往登陆？")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"仍然购买")otherTitle:@[ASLocalizedString(@"前往登录")] clickBlock:^(NSInteger index) {
                if (index == 0) {
                    [self iapWithIndexPath:indexPath model:model];
                }else if (index == 1) {
                    [BDUserModel judgeCurrentUserWithNormalBlock:nil];
                }
            }];
        }else {
            if (curUser.is_auth == NO) {
                [self iapWithIndexPath:indexPath model:model];
            }else{
                BDPayViewController *payVC = [[BDPayViewController alloc] initWithPaySuccessedBlock:^{
                    BDUserModel *user = [BDUserModel getCurrentUser];
                    NSString *cur_url = [NSString stringWithFormat:@"%@users/%@", KBDBaseURL, @(user.user_id)];
                    NSString *headValid = [BDUserModel getHeaderValidation];
                    RACSignal *cur_signal = [[BDNetworkingServer yy_GET:cur_url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
                    [cur_signal subscribeNext:^(id  _Nullable x) {
                        BDUserModel *newUser = [BDUserModel mj_objectWithKeyValues:x];
                        [newUser saveCurrentUser];
                        [self updateInfo];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"vipChange" object:nil];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshFansCount" object:nil];
                    }];
                    [cur_signal subscribeError:^(NSError * _Nullable error) {
                        
                    }];
                }];
                payVC.price = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%@", model[@"money"]]];
                payVC.payType = BDProductPayTypeVIP;
                payVC.productId = model[@"product_id"];
                payVC.product = model;
                [self.navigationController pushViewController:payVC animated:YES];

                
//                BDVipPayView *payView = [BDVipPayView showWithProductId:[model[@"product_id"] integerValue] type:BDPayTypeProduct title:ASLocalizedString(@"购买VIP")product:[NSString stringWithFormat:ASLocalizedString(@"%@ %@天"), model[@"title"], @([model[@"validity"] integerValue] / 3600 / 24)] price:model[@"money"] addressArray:nil];
//                __weak AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//                app.payResultBlock = ^(int state) {
//                    // BDLog(ASLocalizedString(@"支付会调用这个回调回到这个页面"));
//                    app.payResultBlock = nil;
//                    [payView hidden];
//                    if (state == 1) {
//                        [MBManager showBriefAlert:ASLocalizedString(@"支付成功")clickHidden:NO clickBlock:nil];
//                        BDUserModel *user = [BDUserModel getCurrentUser];
//                        NSString *cur_url = [NSString stringWithFormat:@"%@users/%@", KBDBaseURL, @(user.user_id)];
//                        NSString *headValid = [BDUserModel getHeaderValidation];
//                        RACSignal *cur_signal = [[BDNetworkingServer yy_GET:cur_url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
//                        [cur_signal subscribeNext:^(id  _Nullable x) {
//                            BDUserModel *newUser = [BDUserModel mj_objectWithKeyValues:x];
//                            [newUser saveCurrentUser];
//                            [self updateInfo];
//                            [[NSNotificationCenter defaultCenter] postNotificationName:@"vipChange" object:nil];
//                            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshFansCount" object:nil];
//                        }];
//                        [cur_signal subscribeError:^(NSError * _Nullable error) {
//                            
//                        }];
//                    }else if (state == 2) {
//                        [MBManager showBriefAlert:ASLocalizedString(@"支付失败")clickHidden:YES clickBlock:nil];
//                    }else if (state == 3) {
//                        [MBManager showBriefAlert:ASLocalizedString(@"支付取消")clickHidden:YES clickBlock:nil];
//                    }
//                };
            }
        }
    }];
    return cell;
}

- (void)iapWithIndexPath:(NSIndexPath *)indexPath model:(NSDictionary *)model{
    if([SKPaymentQueue canMakePayments]){
        [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
        if (indexPath.row == 0) {
            _currentProId = @"beboy_vip.level1";
        }else if (indexPath.row == 1) {
            _currentProId = @"beboy_vip.level2";
        }
        NSString *url = [NSString stringWithFormat:@"%@payment/IOS/orderInfo", KBDBaseURL];
        NSString *headValid = [BDUserModel getHeaderValidation];
        NSDictionary *para = @{@"id":model[@"product_id"],
                               @"type":@"2"};
        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
            _order_info = x[@"order_info"];
            [self requestProductData:_currentProId];
        }];
        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:ASLocalizedString(@"预下单失败")clickHidden:YES clickBlock:nil];
        }];
        
    }else{
        [MBManager showBriefAlert:ASLocalizedString(@"不允许程序内购买")clickHidden:YES clickBlock:nil];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 180;
}

//去苹果服务器请求商品
- (void)requestProductData:(NSString *)type{
    // BDLog(ASLocalizedString(@"-------------请求对应的产品信息----------------"));
    NSArray *product = [[NSArray alloc] initWithObjects:type,nil];
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
}

//收到产品返回信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
    // BDLog(ASLocalizedString(@"--------------收到产品反馈消息---------------------"));
    NSArray *product = response.products;
    if([product count] == 0){
        [MBManager hideAlert];
        // BDLog(ASLocalizedString(@"--------------没有商品------------------"));
        return;
    }
    
    // BDLog(@"productID:%@", response.invalidProductIdentifiers);
    // BDLog(ASLocalizedString(@"产品付费数量:%lu"),(unsigned long)[product count]);
    
    SKProduct *p = nil;
    for (SKProduct *pro in product) {
        // BDLog(@"%@", [pro description]);
        // BDLog(@"%@", [pro localizedTitle]);
        // BDLog(@"%@", [pro localizedDescription]);
        // BDLog(@"%@", [pro price]);
        // BDLog(@"%@", [pro productIdentifier]);
        
        if([pro.productIdentifier isEqualToString:_currentProId]){
            p = pro;
        }
    }
    
    SKPayment *payment = [SKPayment paymentWithProduct:p];
    
    // BDLog(ASLocalizedString(@"发送购买请求"));
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    [MBManager showBriefAlert:ASLocalizedString(@"支付失败")clickHidden:NO clickBlock:nil];
//    [SVProgressHUD showErrorWithStatus:ASLocalizedString(@"支付失败")];
    // BDLog(ASLocalizedString(@"------------------错误-----------------:%@"), error);
}

- (void)requestDidFinish:(SKRequest *)request{
    [MBManager hideAlert];
    // BDLog(ASLocalizedString(@"------------反馈信息结束-----------------"));
}
 
//监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction{
    for(SKPaymentTransaction *tran in transaction){
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:{
                [MBManager showLoadingAlert:ASLocalizedString(@"等待支付结果")clickHidden:NO clickBlock:nil];
                //从沙盒中获取交易凭证并且拼接成请求体数据
                NSURL *receiptUrl=[[NSBundle mainBundle] appStoreReceiptURL];
                NSData *receiptData=[NSData dataWithContentsOfURL:receiptUrl];
                
                NSString *receiptString=[receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
                NSDictionary *para = @{@"order_info":_order_info,
                                       @"apple_receipt":receiptString};
                [[NSUserDefaults standardUserDefaults]  setObject:para forKey:@"appleNeiGouPara"];
                [self dealApplePayResult];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                
            }
                break;
            case SKPaymentTransactionStatePurchasing:
                // BDLog(ASLocalizedString(@"商品添加进列表"));
                
                break;
            case SKPaymentTransactionStateRestored:{
                // BDLog(ASLocalizedString(@"已经购买过商品"));
                
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            case SKPaymentTransactionStateFailed:{
                // BDLog(ASLocalizedString(@"交易失败"));
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                [MBManager showBriefAlert:ASLocalizedString(@"购买失败")clickHidden:NO clickBlock:nil];
            }
                break;
            default:
                break;
        }
    }
}

- (void)dealApplePayResult{
    NSString *url = [NSString stringWithFormat:@"%@payment/IOS/notify", KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    NSDictionary *para = [[NSUserDefaults standardUserDefaults] objectForKey:@"appleNeiGouPara"];
    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
//        [MBManager hideAlert];
        [MBManager showBriefAlert:ASLocalizedString(@"购买成功")clickHidden:YES clickBlock:nil];
        // BDLog(ASLocalizedString(@"这里需要开始刷新页面"));
        //重新获取当前用户的信息
        BDUserModel *user = [BDUserModel getCurrentUser];
        NSString *cur_url = [NSString stringWithFormat:@"%@users/%@", KBDBaseURL, @(user.user_id)];
        RACSignal *cur_signal = [[BDNetworkingServer yy_GET:cur_url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
        [cur_signal subscribeNext:^(id  _Nullable x) {
            BDUserModel *newUser = [BDUserModel mj_objectWithKeyValues:x];
            [newUser saveCurrentUser];
            [self updateInfo];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"vipChange" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshFansCount" object:nil];
            
//            [[NSUserDefaults standardUserDefaults]  setObject:[NSNull null] forKey:@"appleNeiGouPara"];
        }];
        [cur_signal subscribeError:^(NSError * _Nullable error) {
            
        }];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        [[NSUserDefaults standardUserDefaults]  setObject:[NSNull null] forKey:@"appleNeiGouPara"];
//        [MBManager hideAlert];
        [MBManager showBriefAlert:ASLocalizedString(@"支付失败")clickHidden:YES clickBlock:nil];
    }];
}

//交易结束
- (void)completeTransaction:(SKPaymentTransaction *)transaction{
    // BDLog(ASLocalizedString(@"交易结束"));
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}


- (void)dealloc{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

- (UIButton *)backButton{
    if (!_backButton) {
        self.backButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 40, 25, 25)];
        _backButton.centerY = kBDStatusBarHeight + kBDNavBarHeight / 2.0;
        [_backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    }
    return _backButton;
}

- (UITableView *)tableview{
    if (!_tableview) {
        self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topView.height, kBDScreenWidth, kBDScreenHeight - self.topView.height) style:UITableViewStylePlain];
        _tableview.backgroundColor = [UIColor clearColor];
        _tableview.separatorColor = [UIColor clearColor];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        [self.view addSubview:_tableview];
    }
    return _tableview;
}

- (UIView *)topView{
    if (!_topView) {
        self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0)];
        _topView.backgroundColor = [UIColor colorWithRed:54/255.0 green:54/255.0 blue:54/255.0 alpha:1.0f];
        [_topView addSubview:self.vipImageview];
        _topView.height = self.vipImageview.bottom;
        [self.view addSubview:_topView];
    }
    return _topView;
}

- (UIImageView *)vipImageview{
    if (!_vipImageview) {
        self.vipImageview = [[UIImageView alloc] init];
        _vipImageview.size = CGSizeMake(311 / 375.0 * kBDScreenWidth, 152.5 / 375.0 * kBDScreenWidth);
        _vipImageview.top = kBDTopHeight;
        _vipImageview.centerX = self.topView.width / 2.0;
        _vipImageview.image = [UIImage imageNamed:@"vip_0_pic"];
        [_vipImageview addSubview:self.avatarimageView];
        [_vipImageview addSubview:self.nameLabel];
        [_vipImageview addSubview:self.levelImageView];
        [_vipImageview addSubview:self.timeLabel];
    }
    return _vipImageview;
}

- (UIImageView *)avatarimageView{
    if (!_avatarimageView) {
        self.avatarimageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, 36, 36)];
        _avatarimageView.image = [UIImage imageNamed:@"avatar"];
        _avatarimageView.layer.cornerRadius = 18;
        _avatarimageView.clipsToBounds = YES;
    }
    return _avatarimageView;
}

- (UILabel *)nameLabel{
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc] init];
        _nameLabel.textColor = [UIColor whiteColor];
        _nameLabel.font = [UIFont systemFontOfSize:15];
    }
    return _nameLabel;
}

-(UIImageView *)levelImageView{
    if (!_levelImageView) {
        self.levelImageView = [[UIImageView alloc] init];
    }
    return _levelImageView;
}

- (UILabel *)timeLabel{
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc] init];
        _timeLabel.textColor = [UIColor colorWithWhite:1.0 alpha:0.6f];
        _timeLabel.font = [UIFont systemFontOfSize:10];
    }
    return _timeLabel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
